package com.util;

import java.lang.reflect.Field;

/**
 * Bean Util
 *
 * @author Cc
 * 2024-03-27
 */
public class BeanUtil {
    /**
     * 设置 任意对象 属性
     *
     * @param bean         任意实体
     * @param propertyName 属性名称
     * @param value        值
     * @throws NoSuchFieldException 没有这样字段例外
     */
    public static void setProperty(Object bean, String propertyName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Class<?> beanClass = bean.getClass();

        Field field = beanClass.getDeclaredField(propertyName);

        field.setAccessible(true);

        Object object = typeConversion(field, value);

        field.set(bean, object);
    }

    /**
     * 获取 任意实体 属性值
     *
     * @param bean         任意实体
     * @param propertyName 属性名称
     * @return {@link Object}
     * @throws NoSuchFieldException   没有这样字段例外
     * @throws IllegalAccessException 非法访问例外
     */
    public static Object getProperty(Object bean, String propertyName) throws NoSuchFieldException, IllegalAccessException {
        Class<?> beanClass = bean.getClass();

        Field field = beanClass.getDeclaredField(propertyName);

        field.setAccessible(true);

        return field.get(bean);
    }

    public static void copyProperties(Object source, Object target) throws IllegalAccessException {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        if (targetClass == sourceClass) {
            Field[] fields = sourceClass.getDeclaredFields();
            Field[] declaredFields = targetClass.getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                declaredFields[i].setAccessible(true);

                declaredFields[i].set(target, fields[i].get(source));
            }
        } else
            System.out.println("不是一个玩意");
    }

    /**
     * 类型转换
     * 将 value 转换为 field 字段的 类型
     *
     * @param field 字段
     * @param value 任意类型 值
     * @return {@link Object}
     */
    public static Object typeConversion(Field field, Object value) {
        Class<?> type = field.getType();

        if (value == null) {
            return null;
        }

        if (value.getClass() == type) {
            return value;
        }

        if (type == String.class) {
            return String.valueOf(value);
        } else if (type == Integer.class || type == int.class) {
            return Integer.parseInt(String.valueOf(value));
        } else if (type == Double.class || type == double.class) {
            return Double.parseDouble(String.valueOf(value));
        } else if (type == Float.class || type == float.class) {
            return Float.parseFloat(String.valueOf(value));
        }

        return value;
    }
}
